<template>
  <div>
    <div style="padding-bottom: 64px">
      <infoCard ref="infoCard" />
      <div class="xq-form-wrapper p24 mt24">
        <div style="display: flex; width: 100%; margin-bottom: 16px; justify-content: space-between">
          <titborder>批次详情</titborder>
        </div>
        <div style="margin-bottom: 15px">
          <a-alert message="若进行个税计算的员工未使用本系统报送，算税的同时，系统会将其自动报送至对应税局" type="info" show-icon />
        </div>
        <a-row style="margin-bottom: 15px">
          <a-col :span="12">
            <a-input-search style="width: 180px" v-model="selectName" placeholder="姓名/身份证号" />
          </a-col>
          <a-col :span="12" style="text-align: right">
            <a-button class="mr12" @click="onDownload">导出</a-button>
            <a-button class="mr12" v-if="databatch.status === 1" @click="calculateTaxFeedBackFun">上传算税数据</a-button>
            <a-button type="primary" @click="onSelect" v-if="!stateActive && databatch.status === 1">智能算税</a-button>
            <a-button type="primary" @click="getResults" v-if="stateActive">获取结果</a-button>
          </a-col>
        </a-row>

        <a-spin :spinning="spinning" class="xq-form-content">
          <XqTable
            :customize="FormJson['config']['table']['customize']"
            :scroll="{ x: columns.length * 150 }"
            :pagination="false"
            :dataSource="tableData"
            :columns="columns"
            :rowSelection="
              FormJson['config']['table']['extend']['batch']
                ? {
                    selectedRowKeys: selectedRowKeys,
                    onChange: onSelectChange
                  }
                : null
            "
          >
            <template v-for="(col, index) in columns" v-slot:[`xq_${col.dataIndex}`]>
              <span :key="index">{{ col.customTitle }}</span>
            </template>
            <!-- eslint-disable-next-line prettier/prettier v-slot:[`xq_${col.dataIndex}`]-->
            <template v-for="(col, index) in columns" v-slot:[col.dataIndex]="text, record">
              <div v-if="col.dataIndex === 'identity'" :key="index">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ text }}</span>
                  </template>
                  <div class="overflowsIdentity">{{ text }}</div>
                </a-tooltip>
              </div>
              <div v-else-if="col.dataIndex === 'errorMsg'" :key="index">
                <a-tooltip placement="top" v-if="text">
                  <template slot="title">
                    <span>{{ text }}</span>
                  </template>
                  <div style="color: #fa5051">{{ text ? "失败理由" : "" }}</div>
                </a-tooltip>
              </div>
              <div v-else-if="col.dataIndex === 'tableAction'" :key="index">
                <a-popconfirm title="确定删除该记录吗?" @confirm="() => onDelete(record)">
                  <a v-if="databatch.status === 1">删除</a>
                </a-popconfirm>
              </div>
              <XqTableCell v-else :key="index" :record="record" :field="FormJson['fields'][col.dataIndex]" :dynamicData="dynamicData" />
            </template>
          </XqTable>
          <div class="xq-form-content-pagination">
            <div class="xq-form-content-pagination-total">共 {{ total }} 条</div>
            <a-pagination
              v-model="pageNo"
              :total="total"
              :show-size-changer="true"
              :show-quick-jumper="true"
              :page-size-options="['10', '20', '50', '100']"
              :page-size="pageSize"
              @change="onPageChange"
              @showSizeChange="onPageSizeChange"
            />
          </div>
        </a-spin>
      </div>
      <popUp ref="popVal"></popUp>
      <calculateModel :text="text" :visible.sync="calculateModelVisible" @upDate="upDate" />
    </div>
  </div>
</template>

<script>
import FormJson from "./FormJson";
import XqCurdMixin from "xqjr-plugin-form/mixins/XqCurdMixin";
import infoCard from "../component/infoCard";
import titborder from "../component/titborder";
import calculateModel from "../component/calculateModel";
import {
  getCalculateBatchDetailsList,
  getAllByCompany,
  getCalculateBatchDetails,
  calculateTaxFeedBack,
  getActiveByType,
  deleteAndUpdateById
} from "./api";
import axios from "axios";
import { calculateBatchesGet } from "../component/api";
import popUp from "../../report/component/popUp";
const curdMixin = new XqCurdMixin({
  FormJson,
  tableConfigKey: "table"
});
export default {
  mixins: [curdMixin],
  components: {
    infoCard,
    titborder,
    calculateModel,
    popUp
  },
  data() {
    return {
      stateActive: null,
      text: null,
      spinning: false,
      tableData: [],
      total: 0,
      pageNo: 1,
      pageSize: 20,
      calculateModelVisible: false,
      batchDetail: {},
      selectName: "",
      databatch: {}
    };
  },
  watch: {
    selectName(val) {
      this.onGetTransferAccountsDetails();
    }
  },
  computed: {},
  created() {
    // console.log("this.$route.query.record", this.$route.query.id);
    if (this.$route.query.id) {
      this.infoid = this.$route.query.id;
    }
    this.onGetTransferAccountsDetails();
    this.calculateBatchesGetFun();
  },
  methods: {
    onDelete(e) {
      deleteAndUpdateById(e.id).then((res) => {
        this.confirmLoading = false;
        this.$notification["success"]({
          message: "删除成功"
        });
        this.upDate();
      });
    },
    async calculateBatchesGetFun() {
      try {
        const { data } = await calculateBatchesGet(this.$route.query.id);
        this.databatch = data;
        if (data.status === 4) {
          const field = FormJson.config.table.fields.map((z) => z.title);
          if (!field.includes("错误原因")) {
            FormJson.config.table.fields.push({
              model: "errorMsg",
              title: "错误原因"
            });
          }
        } else {
          const field = FormJson.config.table.fields.map((z) => z.title);
          if (field.includes("错误原因")) {
            FormJson.config.table.fields = FormJson.config.table.fields.filter((z) => z.title !== "错误原因");
          }
        }
        this.getActiveByTypeFun(data.authId);
      } catch (error) {
        console.log("error log --> ", error);
      }
    },
    getActiveByTypeFun(authId) {
      const data = {
        requestType: 4,
        submitType: "calculate",
        companyAuthId: authId
      };
      getActiveByType(data)
        .then((res) => {
          this.stateActive = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    calculateTaxFeedBackFun() {
      this.$router.push({ name: "calculateAdd", query: { pageType: "importPeople", databatch: JSON.stringify(this.databatch) } });
    },
    getResults() {
      const data = {
        batchId: this.databatch.id,
        period: this.databatch.period,
        companyAuthId: this.databatch.authId
      };
      calculateTaxFeedBack(data).then((res) => {
        this.confirmLoading = false;
        this.$notification["success"]({
          message: "操作成功"
        });
        this.upDate();
      });
      // this.text = "反馈";
      // this.calculateModelVisible = true;
    },
    onDownload() {
      const token = this.$store.state.auth.token;
      const columns = this.columns.map((e) => {
        const json = {
          title: e.customTitle,
          dataIndex: e.dataIndex
        };
        if (e.dateFormat) json.dateFormat = e.dateFormat;
        return json;
      });

      axios({
        url: `/tax/api/v1/calculateBatchDetails/export`,
        data: {
          batchId: this.infoid,
          selectName: this.searchName || null,
          exportColumns: columns
        },
        method: "POST",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then((res) => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", `${this.databatch.name}人员导出表.xlsx`);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch((err) => {
          console.log("error log --> ", err);
        });
    },
    async onGetTransferAccountsDetails() {
      try {
        this.visible = false;
        this.spinning = true;
        const { data } = await getCalculateBatchDetailsList({
          batchId: this.infoid,
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          selectName: this.selectName
        });
        this.tableData = data.entities;
        this.total = data.entityCount;
        setTimeout(() => (this.spinning = false), 500);
      } catch (err) {
        console.log("error log --> ", err);
        this.tableData = [];
        this.total = 0;
        setTimeout(() => (this.spinning = false), 500);
      }
    },
    onPageChange(page) {
      this.selectedRowKeys = [];
      this.pageNo = page;
      this.onGetTransferAccountsDetails();
    },
    onPageSizeChange(current, pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.onGetTransferAccountsDetails();
    },
    async onGetAllByCompany() {
      try {
        const { data } = await getAllByCompany("defaultTransferAccounts", {
          moduleType: "hr",
          type: "transferAccounts",
          inUse: true
        });
        if (data && data.length > 0) {
          this.onGetStartApprover(data[0].id);
        } else {
          this.$notification.error({ message: "未设置审批" });
        }
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    onSelect() {
      this.calculateModelVisible = true;
      this.text = "算税";
    },
    upDate(data) {
      // this.$refs.popVal.showModal(data, "获取报送结果");
      this.$refs.infoCard.calculateBatchesGetFun();
      this.onGetTransferAccountsDetails();
      this.calculateBatchesGetFun();
    }
  }
};
</script>

<style lang="scss" scoped>
.overflowsIdentity {
  vertical-align: bottom;
  display: inline-block;
  max-width: 230px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
